package com.study.demo01.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 交换机确认
 * 需要配置 spring.rabbitmq.publisher-confirm-type=correlated
 * 该属性默认是禁用
 * simple 有关闭信道的风险
 */
@Slf4j
//@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback,

        //# 回退消息
        //spring.rabbitmq.publisher-returns=true
        RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * https://www.bilibili.com/video/BV13K4y1H7Zh?p=14&spm_id_from=pageDriver&vd_source=b4e51176bce8c712e65ad9563602762d
     * 确认消息到达了交换机
     * 交换机消息确认回调
     * 1 发送消息 交换机接受到了消息,回调
     * 1.1 correlationData保存了回调消息的ID以及相关信息
     * 1.2  ack=true
     * 1.3 casue null
     * 2 发送消息,交换机接收失败 回调
     * 2.1 correlationData保存了回调消息的ID以及相关信息
     * 2.2 ack=false
     *
     * @param correlationData correlation data for the callback.
     * @param ack             true for ack, false for nack
     * @param cause           An optional cause, for nack, when available, otherwise null.
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData != null ? correlationData.getId() : "";
        if (ack) {
            log.info("交换机收到消息id[{}]", id);
        } else {
            log.info("交换机还未收到id为[{}]的消息,原因是[{}]", id, cause);
        }
    }

    /**
     * Returned message callback.|只有不可达目的地的时候才进行回退|消息没有投递到队列才会触发
     *
     * @param message    the returned message.
     * @param replyCode  the reply code.
     * @param replyText  the reply text.
     * @param exchange   the exchange.
     * @param routingKey the routing key.
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("消息[{}] 被交换机[{}] 退回，原因是[{}],路由key[{}]", new String(message.getBody()), exchange, replyText, routingKey);
    }
}
